const Base = require('./base.js');

module.exports = class extends Base {
  // 获取所有动作
  async getAllActionAction() {
    const value = this.get();
    const openId = value.openId;
    const partId = value.partId;

    let result = await this.model('dynamic_action')
      .where({openId: openId, partId: partId})
      .select();

    if (think.isEmpty(result)) {
      result = await this.model('action').where({partId: partId}).select();
    }

    this.success(result);
  }

  async addOriginAction() {
    const value = this.get();
    const data = JSON.parse(value.data);
    console.log('data', data, typeof data);
    data.map(async(item) => {
      const partId = Math.random().toString(16).substring(2, 10);
      await this.model('part').where({partName: item.name})
        .thenAdd({partId: partId, partName: item.name});
      item.list.map(async(actionItem) => {
        const actionId = Math.random().toString(16).substring(2, 10);
        await this.model('action').where({actionName: actionItem})
          .thenAdd({partId: partId, actionId: actionId, actionName: actionItem});
      });
    });
  }

  async editAction() {
    var value = this.get();
    var { openId, data, partId } = value;
    data = JSON.parse(data);
    var result = data.map(async(item) => {
      var deleteRes = await this.model('dynamic_action')
        .where({
          openId: openId,
          partId: partId,
          actionId: ['<>', item.actionId]
        })
        .delete();
      var updateRes = await this.model('dynamic_action')
        .where({
          openId: openId,
          partId: partId,
          actionId: item.actionId,
          actionName: ['<>', item.actionName]
        })
        .update({
          actionName: item.actionName
        });
      var addRes = await this.model('dynamic_action')
        .where({
          openId: openId,
          partId: partId,
          actionId: ['<>', item.actionId]
        })
        .add({
          openId: openId,
          partId: partId,
          actionId: item.actionId,
          actionName: item.actionName
        });
    });
    if (think.isEmpty(result)) {
      this.fail('edit_error');
    } else {
      this.success(result);
    }
  }

  async addAction() {
    var value = this.get();
    var { openId, actionId, actionName, partId } = value;
    var data = {
      openId: openId,
      partId: partId,
      actionId: actionId,
      actionName: actionName
    };
    var result = await this.model('dynamic_action')
      .where(data)
      .thenAdd(data);

    if (think.isEmpty(result)) {
      this.fail('action_is_exist');
    } else {
      this.success(result);
    }
  }
};
